var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxVideoUserDocModel = function (obj) {
    YjxBaseModel.call(this,obj);
};

YjxVideoUserDocModel.prototype = new YjxBaseModel();

// 取得表名
YjxVideoUserDocModel.prototype.getTableName = function(){
    return 'yjx_video_user_doc';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxVideoUserDocModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'doc_id='+this.doc_id;
};


/**
 * 修改作品名
 *
 * @author 严旭东
 * @date 2017-11-17
 *
 * @param userId 用户唯一标识
 * @param docId 作品唯一标识
 * @param name 用户修改名
 * @param callback  回调
 *          err: 查询失败
 *          results : {}
 */
YjxVideoUserDocModel.prototype.updataVideoUserDocName = function(userId,docId,name,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxVideoUserDocModel.updataVideoUserDoc getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = ' UPDATE yjx.yjx_video_user_doc '+
                   ' SET doc_name ="'+name+'"'+
                   ' WHERE user_id ='+ userId+
                   ' AND uni_doc_id ='+ docId;
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxVideoUserDocModel.updataVideoUserDoc Err: ' + error);
                return callback(error, null);
            }
            return callback(null, results)
        })
    })
};

/**
 * 根据视频作品id获取视频的尺寸
 *
 * @author 李强
 * @date 2017-11-18
 *
 * @param userId 用户唯一标识
 * @param docId 作品唯一标识
 * @param callback  回调
 *          err: 查询失败
 *          results : {w,h}
 */

YjxVideoUserDocModel.prototype.getVideoSize = function(userId,docId,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxVideoUserDocModel.getVideoSize getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = 'SELECT yvr.w,yvr.h ' +
            ' FROM yjx.yjx_video_user_doc yvud,' +
            ' yjx.yjx_video_res yvr,' +
            ' itbour.tg_type tt ' +
            ' WHERE yvud.uni_doc_id=' + docId+
            ' AND yvud.user_id=' +userId+
            ' AND yvud.res_low=yvr.res_id ' +
            ' AND tt.type_id=yvud.type_id ' +
            ' AND yvud.del_flg=0 ' +
            ' AND tt.del_flg=0 ' +
            ' AND yvr.del_flg=0';
        connection.query(sql, function (error, results) {
            connection.release();
            return callback(error, results)
        })
    })
};


/**
 * 根据视频尺寸获取相应的可替换视屏背景的sizeId
 *
 * @author 李强
 * @date 2017-11-18
 *
 * @param w 视频作品的宽
 * @param h 视频作品的高
 * @param callback  回调
 *          err: 查询失败
 *          results : {}
 */
YjxVideoUserDocModel.prototype.getVideoBgsize = function(w,h,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxVideoUserDocModel.getVideoBgDesignList getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        //数字四舍五入（保留n位小数）
        var getFloat = function (number, n) {
            n = n ? parseInt(n) : 0;
            if (n <= 0) return Math.round(number);
            number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n);
            return number;
        };

        var wh_ratio = getFloat(w/h,3);
        var sql = 'SELECT' +
            ' ts.size_id' +
            ' FROM' +
            ' itbour.tg_size ts' +
            ' WHERE ts.wh_ratio=' +wh_ratio +
            ' AND del_flg=0';
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            return callback(error, results)
        })
    })
};



/**
 * sizeId, 可替换视频背景列表的尺寸集合
 * @author 李强
 * @date 2017-11-18
 * @param bForCnt: true [仅用于取count]; false [取数据]
 * @param sizeId:  可替换视频背景列表的尺寸集合
 * @param pageNum: 页码
 * @param pageSize: 页容量
 * @return {string}
 * */
// todo 新增方法, 待审核, begin
function sql_getVideoBgDesignList(bForCnt, sizeIds, pageNum, pageSize){
    var sizeIdSarr = [];
    for(var i=0;i<sizeIds.length;i++){
        sizeIdSarr.push(sizeIds[i].size_id);
    }
    sizeIds = sizeIdSarr.join(",");
    var sql = '';
    if(bForCnt) {
        sql += ' SELECT COUNT(*) AS cnt';
    } else {
        sql += ' SELECT bgs.* , ' +
            ' if(yuts.show_apply_cnt IS NOT NULL, yuts.show_apply_cnt, 0) AS useCounts ';
    }
    sql +=
        ' FROM ( ' +
        ' SELECT tgdd.design_name AS name, ' +
        ' yutd.uni_item_id AS id, ' +
        ' tgdp.thumb AS thumb, ' +
        ' ts.width AS w, ' +
        ' ts.height AS h , ' +
        ' 1 AS opType ' +
        ' FROM itbour.tg_design_doc tgdd, ' +
        ' yjx.yjx_uni_items yutd, ' +
        ' itbour.tg_design_page tgdp, ' +
        ' itbour.tg_size ts, ' +
        ' itbour.tg_type tt ' +
        ' WHERE tgdd.video_size_id ' +
        ' IN ('+sizeIds+') ' +
        ' AND tgdd.design_id = yutd.item_id ' +
        ' AND tgdd.publish = 1 ' +
        ' AND tt.top_parent = 1030 ' +
        ' AND tt.top_parent = yutd.type_id ' +
        ' AND tt.type_id = tgdd.type_id ' +
        ' AND yutd.item_type = 10 ' +
        ' AND tgdp.page_index = 0 ' +
        ' AND ts.size_id = tgdd.size_id ' +
        ' AND tgdp.design_id = tgdd.design_id ' +
        ' AND tgdp.del_flg = 0 ' +
        ' AND yutd.del_flg = 0 ' +
        ' AND tt.del_flg = 0 ' +
        ' AND ts.del_flg = 0 ' +
        ' AND tgdd.del_flg = 0 ' +
        ') bgs ' +
        ' LEFT JOIN yjx.yjx_uni_tmpl_stats yuts ' +
        ' ON yuts.uni_item_id = bgs.id ' +
        ' AND yuts.del_flg = 0'+
        ' ORDER BY ' +
        ' yuts.show_apply_cnt DESC ';

    // 分页
    if(!bForCnt){
        var skipCnt = Number(pageNum||0)*Number(pageSize||0);
        if(Number(pageSize||0)>0){
            sql += " LIMIT " + skipCnt + "," + Number(pageSize);
        }
    }
    return sql;
}

/**
 * 根据背景的尺寸获取相应的视频可替换背景列表
 *
 * @author 李强
 * @date 2017-11-18
 *
 * @param sizeIds 视频可替换背景的尺寸集合
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback  回调
 *          err: 查询失败
 *          results : {}
 */
YjxVideoUserDocModel.prototype.getVideoBgDesignList = function(sizeIds,pageNum,pageSize,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxVideoUserDocModel.getVideoBgDesignList getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = sql_getVideoBgDesignList(false,sizeIds,pageNum,pageSize);
        connection.query(sql, function (error, results) {
            connection.release();
            return callback(error, results);
        })
    })
};




/**
 * 清空 合成视频资源id
 * @author 李强
 * @date 2017-12-25
 * @param userId  用户唯一标识
 * @param docId   统一用户作品id
 * @param callback 回调
 *              err 错误信息
 * */
YjxVideoUserDocModel.prototype.enptyVideoCombRes_v1_0 = function(userId,docId,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxVideoUserDocModel.enptyVideoCombRes_v1_0 Err: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = " UPDATE yjx.yjx_video_user_doc yvud " +
            " SET yvud.comb_res_low = null, " +
            " yvud.comb_res_high = null, " +
            " yvud.comb_res_mid = null " +
            " WHERE yvud.user_id = " + userId+
            " AND yvud.uni_doc_id = " + docId;
        connection.query(sql, function (error, results) {
            connection.release();
            return callback(error);
        })
    })
};





/**
 * 获取可用视频背景列表的数量
 *
 * @author 李强
 * @date 2017-11-18
 *
 * @param sizeIds 视频可替换背景的尺寸集合
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback  回调
 *          err: 查询失败
 *          results : {}
 */
YjxVideoUserDocModel.prototype.getVideoBgDesignListCut = function (sizeIds,pageNum,pageSize,callback) {
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxVideoUserDocModel.getVideoBgDesignListCut getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = sql_getVideoBgDesignList(true,sizeIds,pageNum,pageSize);
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            // 回调
            if(results && results.length>0){
                callback(error, results[0].cnt);
            }else{
                callback(error, 0);
            }
        })
    })
};


/**
 * 获取作品提纲信息(包含尺寸信息)
 *
 * @author 王俊
 * @date 2017-12-2
 *
 * @param productId 作品唯一标识
 * @param userId 用户唯一标识
 * @param callback 回调
 *              err: 错误原因
 *              data: 作品行数据 + 宽+高+单位+模板发布状态
 * */
YjxVideoUserDocModel.prototype.getProductInfo = function(productId, userId, callback){

    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxVideoUserDocModel.getProductInfo Err:'+getConErr);
            return callback(getConErr, null);
        }

        var sql =
            ' SELECT vu.*, ' +
            '        ts.width, ' +
            '        ts.height, ' +
            '        ts.unit, ' +
            '        vd.design_name, ' +
            '        vd.publish AS design_publish, ' +
            '        vd.thumbs as sceneThumbs' +            //  add by 王俊 2018-02-06 增加模板场景图返回
            ' FROM yjx.yjx_video_user_doc vu, ' +
            '      itbour.tg_size ts, ' +
            '      itbour.video_design_doc vd ' +
            ' WHERE vu.doc_id = ' + productId +
            '   AND vu.user_id = ' + userId +
            '   AND vu.del_flg = 0 ' +
            '   AND vu.purpose = 0 ' +
            '   AND ts.size_id = vu.size_id ' +
            '   AND ts.del_flg = 0 ' +
            '   AND vd.design_id = vu.design_id ';

        console.log(sql);
        connection.query(sql, function (error, result) {
            connection.release();

            if(result && result.length>0) {
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }
        });
    });
};

/**
 * 根据 uniId 获取用户视频资源信息
 *
 * @author 王俊
 * @date 2018-03-08
 *
 * @param uniId         统一作品 id
 * @param resLevel      视频资源级别(0, 低; 1, 中; 2, 高;)
 * @param callback      回调
 *          error:      查询失败
 *          videoRes    视频资源(可能为 null)
 */

YjxVideoUserDocModel.prototype.getUniVideoDocRes = function (uniId, resLevel, callback) {
    resLevel = Number(resLevel);
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxVideoUserDocModel.getUniVideoDocRes Err:'+getConErr);
            return callback(getConErr, null);
        }

        var sql =
            ' SELECT yvr.*, ' +
            '        yvud.cover_dur, ' +
            '        yvud.cover_time ' +
            ' FROM yjx.yjx_video_user_doc yvud, ' +
            '      yjx.yjx_video_res yvr ' +
            ' WHERE yvud.uni_doc_id = ' + uniId +
            '   AND yvud.del_flg=0 ' +
            '   AND yvr.del_flg=0 ';
        // 低质量
        if(resLevel === 0) {
            sql += '   AND yvr.res_id = yvud.res_low ';
        }
        // 中质量
        else if (resLevel === 1) {
            sql += '   AND yvr.res_id = yvud.res_mid ';
        }
        // 高质量
        else if (resLevel === 2) {
            sql += '   AND yvr.res_id = yvud.res_high ';
        } else {
            return callback('暂不支持的资源级别: ' + resLevel, null);
        }
        console.log(sql);
        connection.query(sql, function (error, result) {
            connection.release();

            if(result && result.length>0) {
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }
        });
    });
};

//------------------------------------------------------------------
/* 一键秀： 最近一个月    yjx_uni_user_doc的wm_paid为1的统一作品      对应的作品的id
 * 参数：callback：回调，参数如下：
 *          error:错误消息
 *          data: doc_id列表
 */
YjxVideoUserDocModel.prototype.getLastMonthFinishOrderIds= function( callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxVideoUserDocModel.getLastMonthFinishOrderIds Err:'+err);
            return callback(err, null);
        }
        // Use the connection
        var sql =
            " SELECT x1.doc_id, t.uni_doc_id, t.wm_paid"+
            " FROM yjx.yjx_uni_user_doc t"+
            " INNER JOIN ("+
            "		SELECT v.doc_id, v.uni_doc_id"+
            "		FROM yjx.yjx_video_user_doc v"+
            "		WHERE v.del_flg = 0"+
            "	) x1"+
            " ON t.uni_doc_id = x1.uni_doc_id"+
            " WHERE t.del_flg = 0"+
            " AND t.wm_paid = 1"+
            " AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(t.create_time)";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(error){
                return callback(error, null);
            }
            if(!result || result.length==0){
                return callback(null,null);
            }
            var ret = [];
            for(var i=0;i<result.length;i++){
                ret.push(result[i].doc_id);
            }

            return callback(null, ret);
        });
    });
}

module.exports = YjxVideoUserDocModel;